package com.cxs.auth;

import com.cxs.contents.UserContent;
import com.cxs.enums.HospitalErrorResultEnum;
import com.cxs.exception.HospitalException;
import com.cxs.pojo.User;
import com.cxs.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;

import javax.annotation.PostConstruct;

/*
 * @Author:cxs
 * @Date:2021/10/15  11:38
 * @Version 1.0
 * @Motto:放下杂念,只为迎接明天更好的自己
 * */
@Slf4j
public class AuthRealm extends AuthorizingRealm {


    @Autowired
    private UserService userService;

    @PostConstruct
    public void initMatch(){
        HashedCredentialsMatcher matcher = new HashedCredentialsMatcher();
        matcher.setHashIterations(UserContent.INIT_HASH);
        matcher.setHashAlgorithmName("MD5");
        this.setCredentialsMatcher(matcher);
    }


    /**
     * 用户认证
     * @param token
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException,HospitalException {
        // 1. 获取用户输入的用户名
        String loginName = (String) token.getPrincipal();

        if (StringUtils.isEmpty(loginName)){
            log.error("【登录模块】:登录名为空,loginName={}",loginName);
            throw new RuntimeException("【登录模块】:登录名岂能为空");
        }
        // 2. 数据库查询用户
        User user = userService.findUserByUsername(loginName.trim());

        if(StringUtils.isEmpty(user)){
            log.error("【登录模块】:登录名为loginName={}的用户不存在",loginName);
            throw new HospitalException(HospitalErrorResultEnum.USERNAME_PASSWORD_ERROR);
        }

        // 3. 封装返回结果
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user,user.getPwd(),"a");

        info.setCredentialsSalt(ByteSource.Util.bytes(user.getSalt()));

        return info;
    }

    /**
     * 用户授权
     * @param principals
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        return null;
    }
}
